package com.li.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * ControllerAdvice:处理全局数据
 * 最常见的使用场景就是全局异常处理
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    //获取日志对象
    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    /**
     * 异常处理
     * ExceptionHandler:说明这个方法可以处理异常
     * Exception.class:表示Exception级别的异常都可以处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        logger.error("Request URL : {}, Exception : {}",request.getRequestURL(),e);//在控制台打印日志

        //如果处理的这个异常已经有状态了如（404），那么就将它重新抛出，让springboot自动识别错误，去找对应的页面,
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
            throw e;
        }
        ModelAndView mv=new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",e);
        mv.setViewName("error/error");//设置他跳转的路径，为error/error.html
        return mv;
    }
}
